import React, {useEffect, useState} from 'react';
import styled from 'styled-components';

const ButtonWrapper = styled.div`
    display: grid;
    grid-template-columns: repeat(3, 8fr) 5fr;
    grid-template-rows: repeat(4, 1fr);
`;

const RegularButton = styled.button`
    border: none;
    margin: 1px;
    padding: 0.8em 0;
    font-size: 1.5em;
    background-image: linear-gradient(to bottom right, #E0E0E0, #F8F8F8);
`;

const SpecialButton = styled(RegularButton)`
    color: #FD9A16;
    font-size: 1.2em;
`;

const ConfirmButton = styled(RegularButton)`
    font-size: 1.2em;
    grid-row: span 2;
    word-break: break-all;
    color: white;
    background-image: linear-gradient(to bottom right, #FD9A16, #FFCD3C);
`;

type Props = {
    overLengthLock: boolean;
    expression: string,
    onExpressionChange: Function,
    commitData: Function
}

const KeyPad: React.FC<Props> = (props) => {

    const [isFirstChar, setIsFirstChar] = useState(true);
    const [hasDot, setHasDot] = useState(false);

    // 用于调整 hasDot 的值
    useEffect(() => {
        if (props.expression.indexOf('.') === -1) {
            // 不包含 '.'
            setHasDot(false);
        } else {
            if (props.expression.indexOf('+') < props.expression.indexOf('.')) {
                setHasDot(true);
            } else {
                setHasDot(false);
            }
        }
    }, [props.expression]);

    // 用于调整 isFirstChar 的值
    useEffect(() => {
        if (props.expression === '') {
            setIsFirstChar(true);   // 表达式为空，正在输入的是整个表达式的第一个字符
        } else if (props.expression.endsWith('+')) {
            setIsFirstChar(true);   // 加号后是当前数值的第一个字符
        } else {
            setIsFirstChar(false);
        }
    }, [props.expression]);

    const enterDigitSign = (key: string) => {   // 输入 [0123456789]
        // 小数点后已有两位，不可再增加; 如果倒数第3位是'.'，但最后一位不是 '+' 也可以增加
        if (props.expression.slice(-3, -2) !== '.' || (props.expression.slice(-3, -2) === '.' && props.expression.endsWith('+'))) {
            if (key === '0') {  // 0
                if (!isFirstChar) {
                    props.onExpressionChange(props.expression + key);
                }
            } else {            // [1-9]
                props.onExpressionChange(props.expression + key);
            }
        }
    };

    const enterDotSign = () => {    // 输入 '.'
        if (!hasDot) {
            if (isFirstChar) {
                // 当输入的时首个字符时，如果输入'.'，前面自动补0
                props.onExpressionChange(props.expression + '0.');
            } else {
                props.onExpressionChange(props.expression + '.');
            }
        }
    };

    const enterPlusSign = () => {   // 输入 '+'
        // 当要输入的是首个字符时，禁止输入'+'; 当前字符串末尾字符为'.'时，禁止输入'+'
        if (!isFirstChar) {
            const firstWordInExpression = props.expression.split('+')[0];
            const lastWordInExpression = props.expression.split('+')[props.expression.split('+').length - 1];
            if (firstWordInExpression === '' || parseFloat(lastWordInExpression) === 0) {
                alert('亲, 0元咱就别往上加了');  // 当前表达式值为0
                if (props.expression.indexOf('+') === -1) {
                    props.onExpressionChange('');
                } else {
                    props.onExpressionChange(props.expression.slice(0, props.expression.lastIndexOf('+')));
                }
            } else {
                props.onExpressionChange(props.expression + '+');
            }
        }
    };

    const enterDeleteSign = () => { // 输入 '删除'
        if (props.expression === '' || (props.expression.indexOf('+') === -1 && parseFloat(props.expression) === 0)) {
            // 空字符串 或 值为0的字符串
            props.onExpressionChange('');
        } else if (props.expression.endsWith('+')) {
            props.onExpressionChange(props.expression.slice(0, -1));
        } else if (props.expression.endsWith('.')) {
            if (props.expression.endsWith('+0.')) {
                props.onExpressionChange(props.expression.slice(0, -2));
            } else {
                props.onExpressionChange(props.expression.slice(0, -1));
            }
        } else {
            // 当前值去掉最后一位
            props.onExpressionChange(props.expression.slice(0, -1));
        }
    };

    const enterClearSign = () => {
        props.onExpressionChange('')
    };

    const enterConfirmSign = () => {
        props.commitData();
    }

    const handleClick = (event: React.MouseEvent) => {
        if (!props.overLengthLock) {
            const inputKey = (event.target as HTMLButtonElement).textContent;
            if (inputKey === '+') {
                enterPlusSign();
            } else if (inputKey === '.') {
                enterDotSign();
            } else if (inputKey === '删除') {
                enterDeleteSign();
            } else if (inputKey === '清空') {
                enterClearSign();
            } else if (inputKey === '确定') {
                enterConfirmSign();
            } else {
                if (inputKey) {
                    enterDigitSign(inputKey!);
                }
            }
        }
    };

    return (
        <ButtonWrapper onClick={handleClick}>
            <RegularButton>7</RegularButton>
            <RegularButton>8</RegularButton>
            <RegularButton>9</RegularButton>
            <SpecialButton>删除</SpecialButton>
            <RegularButton>4</RegularButton>
            <RegularButton>5</RegularButton>
            <RegularButton>6</RegularButton>
            <SpecialButton>清空</SpecialButton>
            <RegularButton>1</RegularButton>
            <RegularButton>2</RegularButton>
            <RegularButton>3</RegularButton>
            <ConfirmButton>确定</ConfirmButton>
            <SpecialButton>.</SpecialButton>
            <RegularButton>0</RegularButton>
            <SpecialButton>+</SpecialButton>
        </ButtonWrapper>
    );
};

export default KeyPad;